<?php
namespace Modules\Activity\Entities\Fudai;

use Modules\Core\Entities\BaseEntity as Model;

use Setting;

class Record extends Model
{
	protected $guarded = [];
    static public $resourcename = '抽奖记录';
    protected $table = 'fudai_records';

    protected $casts = [
        'sku' => 'json',
        'user' => 'json',
    ];

    static public function beforeGetList($options)
    {
        return $options;
    }

    // 创建榜单
    static public function createWith($package, $order, $node)
    {
    	$user = $order->user;

    	$userInfo = [
    		'name' => $user->name,
    		'headimg' => $user->headimg
    	];

        $arr = [];

        $setting = @Setting::get('sys_fudai_record_list') ?: [];
        $levelIds = @$setting['level_ids'] ?: [];
        
    	foreach ($package->skus as $packageSku) {

            // 如果设置的榜单记录不包含此等级，则不需要记录
            if (!in_array($packageSku->sku_level, $levelIds)) {
                continue;
            }

            // if ($packageSku->sku_level == 1) {
            //     // 等级为1的基础款直接忽略
            //     continue;
            // }

    		$skuInfo = [
    			'title' => $packageSku->title,
    			'thumb' => $packageSku->thumb
    		];

            // $packageSku->sku_level

    		array_push($arr, [
    			'uuid' => uniqid(),
    			'user_id' => $user->id,
    			'sku_id' => $packageSku->sku_id,
    			'user' => json_encode($userInfo),
    			'sku' => json_encode($skuInfo),
    			'level' => $packageSku->sku_level,
                'node_id' => $packageSku->node_id,
                'total' => $packageSku->total,
                'free_order_total' => $packageSku->free_order_total ?: 0,
    			// 'is_special_sku' => $packageSku->is_special_sku,
    			'open_index' => $packageSku->open_index,
    			'created_at' => now(),
    			'updated_at' => now(),
                // 'is_free_order' => $packageSku->is_free_order ?: 0,
                'level_title' => $node->getLevelTitle($packageSku->sku_level)
    		]);
    	}

    	self::insert($arr);
    }
}
